<template>
  <div class="page_main">
    <div class="header">
      <div class="title">广告制作表</div>
      <div class="fill_date">填表日期：{{ cuForm.fill_date || '' }}</div>
    </div>
    <div class="content">
      <el-form size="mini" v-loading="formLoading" ref="cuForm" :model="cuForm" :rules="rules" :disabled="formDisabled">
        <table class="mailTable">
          <tr class="firstTr">
            <td class="firstTd column tip_td">
              类型
            </td>
            <td class="column">
              <el-form-item class="margin-lr-xs text-left" style="margin-bottom: 0;">
                {{ cuForm.type === 1 ? '外单' : '内单' }}
              </el-form-item>
            </td>
            <td class="column tip_td">
              分类
            </td>
            <td class="column">
              <div class="margin-lr-xs text-left">
                <el-tag size="mini" v-if="cuForm.dict_class_out_name">{{ cuForm.dict_class_out_name || '' }}</el-tag>
                <el-tag size="mini" v-if="cuForm.dict_class_in_name">{{ cuForm.dict_class_in_name || '' }}</el-tag>
              </div>
            </td>
          </tr>
          <template v-if="cuForm.type === 1">
            <tr>
              <td class="firstTd column tip_td">
                公司
              </td>
              <td class="column">
                <div class="margin-lr-xs text-left">{{cuForm.dept_name}}</div>
              </td>
              <td class="column tip_td">
                合同
              </td>
              <td class="column">
                <div class="margin-lr-xs text-left">{{cuForm.contract_num}}</div>
              </td>
            </tr>
            <tr>
              <td class="firstTd column tip_td">
                项目
              </td>
              <td class="column">
                <div class="margin-lr-xs text-left">{{cuForm.customer_name}}</div>
              </td>
              <td class="column tip_td">
                市场（时间段）
              </td>
              <td class="column">
                <div class="margin-lr-xs text-left">
                  <el-date-picker v-model="cuForm.daterange_arr" type="daterange" size="mini" range-separator="至"
                    start-placeholder="开始日期" end-placeholder="结束日期" value-format="yyyy-MM-dd" format="yyyy年MM月dd日"
                    readonly />
                </div>
              </td>
            </tr>
          </template>
          <!-- 内单显示字段 -->
          <template v-else-if="cuForm.type === 2">
            <tr>
              <td class="firstTd column tip_td">
                公司
              </td>
              <td colspan="3" class="column">
                <div class="margin-lr-xs text-left">{{cuForm.dept_name}}</div>
              </td>
            </tr>
            <tr>
              <td class="firstTd column tip_td">
                合同
              </td>
              <td class="column">
                <div class="margin-lr-xs text-left">{{cuForm.contract_num}}</div>
              </td>
              <td class="column tip_td">
                项目
              </td>
              <td class="column">
                <div class="margin-lr-xs text-left">{{cuForm.customer_name}}</div>
              </td>
            </tr>
          </template>


          <!-- 画面 -->
          <tr>
            <td class="firstTd column tip_td">
              画面
            </td>
            <td colspan="3" class="column">
              <div class="flex flex-wrap align-center margin-top-sm">
                <div class="flex flex-direction align-center justify-between margin-left"
                  v-for="(item,index) in cuForm.pics" :key="index">
                  <el-image style="width: 100px;height: 160px;" :src="item.pic_url" fit="contain"
                    :preview-src-list="picList">
                  </el-image>
                  <div>{{ item.uuid }}</div>
                </div>
              </div>
            </td>
          </tr>


          <!-- 历史制作单，外单才会显示 -->
          <tr v-if="cuForm.type === 1 && tableDataHistory.length">
            <td class="firstTd column tip_td">
              历史制作单
            </td>
            <td colspan="3" class="column">
              <el-card style="margin: 15px 0;padding: 0 20px 20px 20px;">
                <el-table :data="tableDataHistory" size="mini" style="width: 100%">
                  <el-table-column label="历史制作单" min-width="100" align="center" show-overflow-tooltip>
                    <template slot-scope="{row,$index}">
                      <el-tag size="mini">{{ row.daterange_start + '~' + row.daterange_start }}</el-tag>
                    </template>
                  </el-table-column>
                  <el-table-column label="生成状态" min-width="100" align="center">
                    <template slot-scope="{row,$index}">
                      <el-tag size="mini" v-if="row.gen_status===1">未生成</el-tag>
                      <el-tag type="warning" size="mini" v-if="row.gen_status===2">部分生成</el-tag>
                      <el-tag type="success" size="mini" v-if="row.gen_status===3">全部生成</el-tag>
                    </template>
                  </el-table-column>
                  <el-table-column label="提交时间" min-width="100" align="center" show-overflow-tooltip>
                    <template slot-scope="{row,$index}">
                      {{ row.created_at ? row.created_at.substring(0, 10) : '' }}
                    </template>
                  </el-table-column>
                  <el-table-column prop="b" label="通过时间" min-width="100" align="center" show-overflow-tooltip>
                    <template slot-scope="{row,$index}">
                      {{ row.flow_passed_at ? row.flow_passed_at.substring(0, 10) : '' }}
                    </template>
                  </el-table-column>
                  <el-table-column prop="mark_name" label="标记类型" min-width="100" align="center" />
                  <el-table-column prop="mark_memo" label="备注" min-width="100" align="center" />
                </el-table>
              </el-card>
            </td>
          </tr>


          <!-- 供应商 -->
          <tr>
            <td class="firstTd column tip_td">
              <span class="tip">*</span>分配供应商、小样配送
            </td>
            <td colspan="3" class="column">
              <el-card style="margin: 15px 0;padding: 0 20px 20px 20px;"
                v-if="cuForm.bill_market_id || tableDataMedia.length">
                <el-divider content-position="center">
                  <div class="text-bold">
                    <span class="text-green">分配供应商</span>
                  </div>
                </el-divider>
                <div class="margin-bottom-sm text-right" style="margin-top: -15px;">
                  <el-button type="primary" size="mini" icon="el-icon-circle-plus-outline" @click="showSupplier()">
                    分配供应商
                  </el-button>
                </div>
                <el-table :data="tableDataSupplier" class="dataTable" size="mini" border style="width: 100%">
                  <el-table-column prop="supplier_name" label="供应商" min-width="100" align="center" />
                  <el-table-column prop="media_pic_type" label="材质" min-width="100" align="center" />
                  <el-table-column label="画面" min-width="100" align="center">
                    <template slot-scope="{row,$index}">
                      <div class="flex flex-wrap" v-if="row.choose_info && row.choose_info.length">
                        <div class="margin-left-sm text-bold" v-for="(val,idx) in row.choose_info"
                          :key="val.name">{{ val.name + '（ ' + val.size_width + 'cm*' + val.size_height + 'cm --- ' + val.count +' ）' }}</div>
                      </div>
                    </template>
                  </el-table-column>
                  <el-table-column label="操作" min-width="100" align="center">
                    <template slot-scope="{row,$index}">
                      <el-button type="text" size="mini" class="margin-left" @click="delSupplierRow($index)">删除
                      </el-button>
                    </template>
                  </el-table-column>
                </el-table>


                <!-- 小样 -->
                <template v-if="cuForm.has_sample">
                  <el-divider content-position="center">
                    <div class="text-bold">
                      <span class="text-red">小样配送</span>
                    </div>
                  </el-divider>

                  <el-table :data="tableDataSampleDeliver" class="own-table" size="mini" border style="width: 100%">
                    <el-table-column prop="supplier_name" label="供应商" min-width="100" align="center" />
                    <el-table-column label="配送方式" min-width="100" align="center">
                      <template slot-scope="{row,$index}">
                        <el-form-item prop="rulesComm" :rules="rulesComm('select', '配送方式', row.type)">
                          <el-select v-model="row.type" placeholder="请选择配送方式" style="width: 100%;">
                            <el-option v-for="item in deliverTypeSampleList" :key="item.id" :label="item.name"
                              :value="item.id">
                            </el-option>
                          </el-select>
                        </el-form-item>
                        <el-form-item prop="rulesComm" :rules="rulesComm('select', '跑腿平台', row.run_id)"
                          style="margin-top: 0 !important;" v-if="row.type==3">
                          <el-select v-model="row.run_id" placeholder="请选择跑腿平台" style="width: 100%;">
                            <el-option v-for="item in dictRunArr" :key="item.id" :label="item.name" :value="item.id">
                            </el-option>
                          </el-select>
                        </el-form-item>
                        <el-form-item prop="rulesComm" :rules="rulesComm('price', '跑腿费', row.run_cost)"
                          v-if="row.type==3">
                          <el-input clearable v-model.trim="row.run_cost" placeholder="请输入跑腿费">
                          </el-input>
                        </el-form-item>
                      </template>
                    </el-table-column>
                    <el-table-column prop="address" label="地址" min-width="100" align="center">
                      <template slot-scope="{row,$index}">
                        <el-form-item :prop="row.type==4?'rulesCommNoRequired':'rulesComm'"
                          :rules="row.type==4?rulesCommNoRequired('textarea', '地址', row.address):rulesComm('textarea', '地址', row.address)">
                          <el-input clearable type="textarea" :rows="1" v-model.trim="row.address" placeholder="请输入地址">
                          </el-input>
                        </el-form-item>
                      </template>
                    </el-table-column>
                  </el-table>
                </template>
              </el-card>
            </td>
          </tr>


          <!-- 配送方式 -->
          <tr v-if="cuForm.type===1 && tableDataSupplier.length">
            <td class="firstTd column tip_td">
              <span class="tip">*</span>配送方式
            </td>
            <td colspan="3" class="column">
              <el-card style="margin: 15px 0;padding: 0 20px 20px 20px;">
                <el-table :data="tableDataDeliver" class="own-table" size="mini" style="width: 100%">
                  <el-table-column prop="supplier_name" label="供应商" min-width="100" align="center" />
                  <el-table-column label="配送方式" min-width="100" align="center">
                    <template slot-scope="{row,$index}">
                      <el-form-item prop="rulesComm" :rules="rulesComm('select', '配送方式', row.type)">
                        <el-select v-model="row.type" placeholder="请选择配送方式" style="width: 100%;">
                          <el-option v-for="item in deliverTypeList" :key="item.id" :label="item.name" :value="item.id">
                          </el-option>
                        </el-select>
                      </el-form-item>
                      <el-form-item prop="rulesComm" :rules="rulesComm('select', '跑腿平台', row.run_id)"
                        style="margin-top: 0 !important;" v-if="row.type==3">
                        <el-select v-model="row.run_id" placeholder="请选择跑腿平台" style="width: 100%;">
                          <el-option v-for="item in dictRunArr" :key="item.id" :label="item.name" :value="item.id">
                          </el-option>
                        </el-select>
                      </el-form-item>
                      <el-form-item prop="rulesComm" :rules="rulesComm('price', '跑腿费', row.run_cost)"
                        v-if="row.type==3">
                        <el-input clearable v-model.trim="row.run_cost" placeholder="请输入跑腿费">
                        </el-input>
                      </el-form-item>
                    </template>
                  </el-table-column>
                  <el-table-column prop="hope_time" label="期望送达时间" min-width="100" align="center">
                    <template slot-scope="{row,$index}">
                      <el-form-item prop="rulesComm" :rules="rulesComm('text', '期望送达时间', row.hope_time)">
                        <el-date-picker clearable v-model="row.hope_time" type="datetime" placeholder="选择期望送达时间"
                          value-format="yyyy-MM-dd HH:mm:ss" style="width: 100%;">
                        </el-date-picker>
                      </el-form-item>
                    </template>
                  </el-table-column>
                  <el-table-column prop="address" label="地址" min-width="100" align="center">
                    <template slot-scope="{row,$index}">
                      <el-form-item prop="rulesComm" :rules="rulesComm('textarea', '地址', row.address)">
                        <el-input clearable type="textarea" :rows="1" v-model.trim="row.address" placeholder="请输入地址">
                        </el-input>
                      </el-form-item>
                    </template>
                  </el-table-column>
                  <el-table-column prop="memo" label="备注" min-width="100" align="center">
                    <template slot-scope="{row,$index}">
                      <el-form-item>
                        <el-input clearable type="textarea" :rows="1" v-model.trim="row.memo" placeholder="请输入备注">
                        </el-input>
                      </el-form-item>
                    </template>
                  </el-table-column>
                </el-table>
              </el-card>
            </td>
          </tr>


          <tr>
            <td class="firstTd colum tip_td">
              备注
            </td>
            <td colspan="3" class="column" style="padding: 15px 10px">
              <el-input v-model.trim="cuForm.memo" type="textarea" :rows="4"></el-input>
            </td>
          </tr>
        </table>
      </el-form>
    </div>
    <div class="margin-bottom">
      <FlowBtnRow :is-new-data="params.is_create" :is-applyer="cuForm.flow_applyer_id == userId"
        :flow-status="cuForm.flow_status" :can-check="cuForm.can_check" @save="save" @submit="submit" @pass="pass"
        @returnBack="returnBack" @delete="remove" @actualDelete="actualDelete" :is-confirm="false" form-name=""
        :flowType="21" :dataId="(params || {}).id"></FlowBtnRow>
    </div>


    <!-- 分配供应商(弹出框) -->
    <el-dialog title="选择画面" :visible.sync="dialogVisibleFrameSupplier" width="60%" center>
      <el-form :model="cuFormFrameSupplier" ref="cuFormFrameSupplier" v-loading="dialogLoading" size="mini">
        <table class="mailTable" style="width: 100%;">
          <tr class="firstTr">
            <td class="firstTd column tip_td">
              分配供应商
            </td>
            <td colspan="3" class="column">
              <el-card style="margin: 15px 0;padding: 0 20px 20px 20px;">
                <el-table :data="tableDataFrameSupplier" size="mini" style="width: 100%">
                  <el-table-column label="画面(幅)" min-width="100" align="center">
                    <template slot-scope="{row,$index}">
                      <template v-if="row.choose_info && row.choose_info.length">
                        <span class="margin-left-sm text-bold" v-for="(val,idx) in row.choose_info"
                          :key="val.name">{{ val.name +'（' + val.count +'）' }}</span>
                      </template>
                    </template>
                  </el-table-column>
                  <el-table-column prop="media_pic_type" label="材质" min-width="100" align="center" />
                  <el-table-column label="供应商" min-width="100" align="center">
                    <template slot-scope="{row,$index}">
                      <el-form-item prop="rulesComm" :rules="rulesComm('select', '供应商', row.supplier_info)">
                        <el-select size="mini" v-model="row.supplier_info" value-key="id" placeholder="请选择供应商"
                          style="width: 100%;margin-top: 18px;">
                          <el-option v-for="item in supplierObj[row.media_pic_type_id]" :key="item.id"
                            :label="item.name" :value="item">
                          </el-option>
                        </el-select>
                      </el-form-item>
                    </template>
                  </el-table-column>
                </el-table>
              </el-card>
            </td>
          </tr>
          <tr>
            <td class="firstTd column tip_td">
              示例图
            </td>
            <td colspan="3" class="column">
              <div class="flex flex-wrap align-center margin-top-sm">
                <div class="flex flex-direction align-center justify-between margin-left"
                  v-for="(item,index) in cuForm.pics" :key="index">
                  <el-image style="width: 100px;height: 160px;" :src="item.pic_url" fit="contain"
                    :preview-src-list="picList">
                  </el-image>
                  <div>{{ item.uuid }}</div>
                </div>
              </div>
            </td>
          </tr>
        </table>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisibleFrameSupplier = false">取 消</el-button>
        <el-button type="primary" @click="onSubmitFrameSupplier">确 定</el-button>
      </span>
    </el-dialog>


  </div>
</template>

<script>
  import { list_by_material_id } from '@/api/supplier/supplier'
  import { list_all3rd_bycode } from '@/api/business/setting/dict'
  import {
    get_deliver_type,
    detail,
    save,
    begin,
    pass,
    return_back,
    remove,
    actual_delete
  } from '@/api/business/ad_make_order'

  import { cloneDeep } from 'lodash'
  import FlowBtnRow from '@/components/FlowBtnRow/index'
  import common from '@/utils/common.js'
  import { formatDateByFmt } from '@/utils/util'

  export default {
    name: 'LookAdMakeOrderDetail',
    components: {
      FlowBtnRow
    },
    data() {
      /**
       * 校验公共类
       *
       * type: text(输入框) select(下拉框) count(数值输入框) textarea(文本框)
       * required: 是否校验
       * message: 校验失败显示内容
       * data: 数据
       * params: 参数object类型
       * callback: 回调函数
       */
      var validatorComm = (type, required, message, data, params, callback) => {
        if (data) {
          if (type === 'count') {
            if (!/^[0-9]+[0-9]*[0-9]*$/.test(data)) callback(new Error('请输入正整数'))
            if (params && +params < data) callback(new Error('允许输入的最大数量为' + params))
          }
          if (type === 'price')
            if (!/^(([1-9]{1}\d*)|(0{1}))(\.\d{1,2})?$/.test(data)) callback(new Error('请输入合法数字(支持2位小数)'))
          if (type === 'textarea')
            if (params && params < data.length) callback(new Error('允许输入最多' + params + '个字符串'))
          callback();
        } else if (required) callback(new Error((type === 'select' ? '请选择' : '请输入') + message)) // 验证不通过
        callback(); // 验证通过
      }

      return {
        cuForm: {
          type: 1,
          dept_id: null,
          contract_id: null,
          customer_id: null,
          bill_market_id: null,
          dict_class_out_id: null,
          dict_class_in_id: null,
          memo: null,
          marks: [],
          pics: [],
          diss: [],
          delivers: [],
          contract_info: null,
          daterange_start: null,
          daterange_end: null,
          dict_class_out_name: null,
          has_sample: false,
        },
        rules: {
          dept_id: [
            { required: true, message: '请选择公司', trigger: 'change' }
          ],
          contract_id: [
            { required: true, message: '请选择合同', trigger: 'change' }
          ],
          contract_info: [
            { required: true, message: '请选择合同', trigger: 'change' }
          ],
          customer_id: [
            { required: true, message: '请选择项目', trigger: 'change' }
          ],
          bill_market_id: [
            { required: true, message: '请选择时间段', trigger: 'change' }
          ],
        },
        rulesCommNoRequired: (type, content, data) => {
          return [{
            validator: (rule, value, callback) => {
              validatorComm(type, false, content, data, 200, callback)
            },
            trigger: type === 'select' ? 'change' : 'blur'
          }]
        },
        rulesComm: (type, content, data) => {
          return [{
            validator: (rule, value, callback) => {
              validatorComm(type, true, content, data, 200, callback)
            },
            trigger: type === 'select' ? 'change' : 'blur'
          }]
        },
        rulesCount: (maxCount, data) => {
          return [{
            validator: (rule, value, callback) => {
              validatorComm('count', false, '', data, +maxCount, callback)
            },
            trigger: 'blur'
          }]
        },
        params: {},
        supplierObj: {},
        dictRunArr: [],
        // 历史单
        tableDataHistory: [],
        // 点位详情相关数据
        picList: [], // 画面url数组，用于预览
        tableDataMedia: [],
        // 分配供应商相关数据
        dialogVisibleFrameSupplier: false,
        cuFormFrameSupplier: {},
        tableDataFrameSupplier: [],
        tableDataSupplier: [],
        tableDataSampleDeliver: [],
        tableDataDeliver: [],
        deliverTypeSampleList: [], // 小样配送方式
        deliverTypeList: [], // 配送方式
        runPlatformList: [],

        formLoading: false,
        dialogLoading: false,
      }
    },
    watch: {},
    computed: {
      userId() {
        return this.$store.state.user.id
      },
      formDisabled() {
        return this.cuForm.flow_status == 3 || this.cuForm.flow_status == 4
      }
    },
    created() {
      const uuid = this.$route.query.uuid
      const params = this.$store.state.keep.pageParamsMap.get(uuid)
      this.params = params
      if (params.id || params.handle_param) {
        let id = null
        if (params.id) id = params.id
        else id = params.handle_param.id
        this.getDetail(id)
      }
      // 初始化
      this.getDeliverTypeSampleList()
      this.getDeliverTypeList()
      this.getDictRunList()
    },
    methods: {
      // api请求
      getDetail(id) {
        const that = this
        this.formLoading = true
        detail({ id: id }).then(res => {
          let {
            data
          } = res
          const type = data.type === 'OUT' ? 1 : 2,
            markVOList = data.markVOList,
            picVOList = data.picVOList,
            disVOList = data.disVOList,
            deliverVOList = data.deliverVOList,
            history_list = [],
            supplier_obj = {},
            supplier_list = [],
            sample_deliver_list = [],
            deliver_list = []
          // 处理分配供应商
          for (var i in disVOList) {
            var o = disVOList[i],
              supplier_id = o.supplier_id,
              pic_type_id = o.pic_type_id,
              pic_uuid = o.pic_uuid,
              num = o.num,
              size_width = o.size_width,
              size_height = o.size_height
            if (supplier_obj[supplier_id + '_' + pic_type_id]) {
              if (supplier_obj[supplier_id + '_' + pic_type_id].choose_info[pic_uuid]) supplier_obj[supplier_id +
                  '_' + pic_type_id].choose_info[pic_uuid]
                .count += num
              else supplier_obj[supplier_id + '_' + pic_type_id].choose_info[pic_uuid] = {
                name: pic_uuid,
                count: num,
                size_width: size_width,
                size_height: size_height
              }
            } else {
              supplier_obj[supplier_id + '_' + pic_type_id] = {
                supplier_id: supplier_id,
                supplier_name: o.supplier,
                media_pic_type_id: o.pic_type_id,
                media_pic_type: o.pic_type,
                choose_info: {}
              }
              supplier_obj[supplier_id + '_' + pic_type_id].choose_info[pic_uuid] = {
                name: pic_uuid,
                count: num,
                size_width: size_width,
                size_height: size_height
              }
            }
          }
          for (var i in supplier_obj) {
            var o = supplier_obj[i],
              choose_info_obj = o.choose_info,
              choose_info = []
            for (var x in choose_info_obj) {
              choose_info.push(choose_info_obj[x])
            }
            var obj = Object.assign({}, o)
            obj.choose_info = choose_info
            supplier_list.push(obj)
          }
          // 处理配送数据
          for (var i in deliverVOList) {
            var o = deliverVOList[i],
              item = {
                supplier_id: o.supplier_id,
                supplier_name: o.supplier,
                type: o.type,
                run_id: o.run_id,
                run_cost: o.run_cost,
                address: o.address
              }
            if (o.sample == 1) {
              sample_deliver_list.push(item)
            } else {
              item.hope_time = o.hope_time
              item.memo = o.memo
              deliver_list.push(item)
            }
          }

          this.cuForm = data
          this.cuForm.type = type
          this.cuForm.daterange_arr = [data.daterange_start, data.daterange_end]
          this.cuForm.fill_date = formatDateByFmt(data.created_at, 'yyyy-MM-dd')
          this.cuForm.pics = picVOList.map((item, index) => {
            return {
              uuid: item.uuid,
              pic_url: item.pic_url
            }
          })
          this.picList = picVOList.map((item, index) => {
            return item.pic_url
          })
          this.tableDataMedia = disVOList
          this.tableDataHistory = markVOList
          this.tableDataSupplier = supplier_list
          this.tableDataSampleDeliver = sample_deliver_list
          this.tableDataDeliver = deliver_list
          this.formLoading = false
        })
      },
      getSupplierObj(materialId) {
        list_by_material_id({ materialId: materialId }).then(res => {
          this.$set(this.supplierObj, materialId, res.data.map(item => {
            return {
              id: item.id,
              name: item.name
            }
          }))
        })
      },
      getDeliverTypeSampleList() {
        get_deliver_type({ isSample: 1 }).then(res => {
          this.deliverTypeSampleList = res.data
        })
      },
      getDeliverTypeList() {
        get_deliver_type({ isSample: 0 }).then(res => {
          this.deliverTypeList = res.data
        })
      },
      getDictRunList() {
        list_all3rd_bycode({ code: 'zzdxg-ptpt' }).then(res => {
          this.dictRunArr = res.data.map(item => {
            return {
              id: item.id,
              name: item.name
            }
          })
        })
      },
      // 事件
      showSupplier() { // 分配供应商(弹出框)相关事件
        this.dialogVisibleFrameSupplier = true
        this.dialogLoading = true
        // 根据画面(幅) 和 材质处理数据
        const tableData = this.tableDataMedia
        var list = [],
          obj = {},
          material_obj = {} // 材质obj
        for (var i in tableData) {
          var o = tableData[i],
            pic_uuid = o.pic_uuid,
            pic_type_id = o.pic_type_id,
            count = o.num
          if (obj[pic_uuid + '_' + pic_type_id]) {
            obj[pic_uuid + '_' + pic_type_id].choose_info[0].count += count
          } else {
            obj[pic_uuid + '_' + pic_type_id] = {
              choose_info: [{
                name: pic_uuid,
                count: count
              }],
              media_pic_type_id: o.pic_type_id,
              media_pic_type: o.pic_type
            }
          }
          material_obj[pic_type_id] = pic_type_id
        }
        for (var i in obj) {
          var o = obj[i]
          list.push(o)
        }
        // 请求供应商列表
        for (var i in material_obj) {
          this.getSupplierObj(i)
        }
        if (!list.length) {
          this.$message.error('暂无分配画面数据')
          return false
        }
        this.$nextTick(() => {
          this.$refs['cuFormFrameSupplier'].resetFields()
          this.tableDataFrameSupplier = list
          this.dialogLoading = false
        })
      },
      onSubmitFrameSupplier() {
        this.$refs['cuFormFrameSupplier'].validate((valid) => {
          if (valid) {
            const tableData = this.tableDataFrameSupplier
            var list = [],
              obj = {},
              supplierList = [],
              supplierObj = {}
            for (var i in tableData) {
              var o = tableData[i],
                supplier_info = o.supplier_info,
                supplier_id = supplier_info.id,
                supplier_name = supplier_info.name,
                media_pic_type_id = o.media_pic_type_id
              if (obj[supplier_id + '_' + media_pic_type_id]) {
                obj[supplier_id + '_' + media_pic_type_id].choose_info.push(o.choose_info[0])
              } else {
                obj[supplier_id + '_' + media_pic_type_id] = {
                  supplier_id: supplier_id,
                  supplier_name: supplier_name,
                  media_pic_type_id: o.media_pic_type_id,
                  media_pic_type: o.media_pic_type,
                  choose_info: o.choose_info
                }
              }
            }
            for (var i in obj) {
              var o = obj[i],
                supplier_id = o.supplier_id
              list.push(o)
              if (!supplierObj[supplier_id]) {
                supplierObj[supplier_id] = {
                  supplier_id: supplier_id,
                  supplier_name: o.supplier_name,
                }
              }
            }
            for (var i in supplierObj) {
              supplierList.push(supplierObj[i])
            }
            this.tableDataSupplier = list
            // 外单才有小样配送、配送方式数据
            if (this.cuForm.type === 1) {
              if (this.cuForm.has_sample) this.tableDataSampleDeliver = cloneDeep(supplierList)
            }
            this.tableDataDeliver = cloneDeep(supplierList)
            this.dialogVisibleFrameSupplier = false
            this.$nextTick(() => {
              this.$refs['cuForm'].clearValidate()
            })
          }
        })
      },
      editSupplierRow(row, index) {

      },
      delSupplierRow(index) {
        const supplier_id = this.tableDataSupplier[index].supplier_id
        const index2 = this.tableDataSampleDeliver.findIndex((item) => {
          return supplier_id === item.supplier_id;
        });
        const index3 = this.tableDataDeliver.findIndex((item) => {
          return supplier_id === item.supplier_id;
        });
        this.tableDataSupplier.splice(index, 1)
        this.tableDataSampleDeliver.splice(index2, 1)
        this.tableDataDeliver.splice(index3, 1)
      },
      // 审批流组件相关方法
      checkData(content, callback) {
        this.$refs['cuForm'].validate((valid) => {
          if (valid) {
            const tableDataSupplier = this.tableDataSupplier
            if (!tableDataSupplier.length) {
              this.$message.error('请分配供应商')
              return false
            }

            const cuForm = this.cuForm,
              tableDataMedia = this.tableDataMedia,
              tableDataSampleDeliver = this.tableDataSampleDeliver,
              tableDataDeliver = this.tableDataDeliver
            var marks = [],
              diss = [],
              delivers = [],
              frameObj = {} // 画面对应的供应商
            // 标记制作单

            // 分配供应商
            for (var x in tableDataSupplier) {
              var o = tableDataSupplier[x],
                choose_info = o.choose_info
              for (var y in choose_info) {
                var item = choose_info[y]
                frameObj[item.name + '_' + o.media_pic_type_id] = o.supplier_id
              }
            }
            for (var i in tableDataMedia) {
              var o = tableDataMedia[i],
                name = o.pic_uuid,
                media_pic_type_id = o.pic_type_id
              diss.push({
                pic_uuid: name,
                pic_type_id: media_pic_type_id,
                supplier_id: frameObj[name + '_' + media_pic_type_id],
                size_width: o.size_width,
                size_height: o.size_height,
                num: o.num
              })
            }
            // 配送方式
            for (var i in tableDataDeliver) {
              var o = tableDataDeliver[i]
              o.sample = 0
              delivers.push(o)
            }
            // 小样配送
            for (var i in tableDataSampleDeliver) {
              var o = tableDataSampleDeliver[i]
              o.sample = 1
              delivers.push(o)
            }
            var formData = {
              id: cuForm.id,
              customer_id: cuForm.customer_id,
              pics: cuForm.pics,
              memo: cuForm.memo
            }
            formData.marks = []
            formData.diss = diss
            formData.delivers = delivers
            console.log('formData', formData)
            common.confirmDialog(content).then((confirm) => {
              if (confirm) {
                if (callback && typeof callback === 'function') callback(formData)
              }
            })
          }
        })
      },
      save() {
        this.checkData('您确定要保存?', (formData) => {
          const loading = this.$loading({
            lock: true,
            text: '保存中',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
          })
          save(formData).then(res => {
            loading.close()
            this.$message.success('保存成功')
            this.closeThisPage()
          }).catch(() => {
            loading.close()
          })
        })
      },
      submit() {
        this.checkData('您确定要提交?', (formData) => {
          const loading = this.$loading({
            lock: true,
            text: '提交中',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
          })
          begin(formData).then(res => {
            loading.close()
            this.$message.success('提交成功')
            this.closeThisPage()
          }).catch(() => {
            loading.close()
          })
        })
      },
      pass(opinion) {
        const loading = this.$loading({
          lock: true,
          text: '加载中',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })
        pass({ id: this.cuForm.id, wf_check_opinion: opinion }).then(res => {
          this.$message.success('操作成功')
          this.closeThisPage()
          loading.close()
        }).catch(() => {
          loading.close()
        })
      },
      returnBack(opinion) {
        const loading = this.$loading({
          lock: true,
          text: '加载中',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })
        return_back({ id: this.cuForm.id, wf_check_opinion: opinion }).then(res => {
          this.$message.success('操作成功')
          this.closeThisPage()
          loading.close()
        }).catch(() => {
          loading.close()
        })
      },
      remove() {
        const loading = this.$loading({
          lock: true,
          text: '加载中',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })
        remove({ id: this.cuForm.id }).then(res => {
          this.$message.success('操作成功')
          this.closeThisPage()
          loading.close()
        }).catch(() => {
          loading.close()
        })
      },
      actualDelete() {
        const loading = this.$loading({
          lock: true,
          text: '加载中',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })
        actual_delete({ id: this.cuForm.id }).then(res => {
          this.$message.success('操作成功')
          this.closeThisPage()
          loading.close()
        }).catch(() => {
          loading.close()
        })
      },
      // 关闭此页面
      closeThisPage() {
        this.$store.dispatch('tagsView/closePage', this.$route.name)
      },

    }
  }
</script>

<style scoped>
  .title {
    margin-top: 20px;
    font-size: 25px;
    font-weight: bold;
    text-align: center;
  }

  .header {
    width: 80%;
    margin: 0 auto;
    position: relative;
  }

  .content {
    margin-top: 20px;
  }

  .fill_date {
    font-weight: bold;
    position: absolute;
    right: 0;
    top: 16px;
    line-height: 25px;
  }

  .mailTable {
    width: 80%;
    font-size: 14px;
    margin: 0 auto 10px auto;
    border-collapse: collapse;
  }

  .mailTable tr td {
    height: 60px;
    line-height: 35px;
    box-sizing: border-box;
    padding: 0 10px;
    border-bottom: 1px solid #E6EAEE;
    border-right: 1px solid #E6EAEE;
    text-align: center;
  }

  .firstTr td {
    border-top: 1px solid #E6EAEE;
  }

  .firstTd {
    border-left: 1px solid #E6EAEE;
  }

  .mailTable tr td.column {
    text-align: center;
  }

  .tip {
    color: red;
    width: 200px;
  }

  .table-herder {
    background-color: #F5F7FA;
    font-weight: bold;
  }

  .tip_td {
    padding: 0 20px !important;
    background-color: #F5F7FA;
    font-weight: bold;
    width: 200px;
  }

  /deep/ .content .el-form-item {
    margin-bottom: 0;
  }

  /deep/ .el-card .el-card__body {
    padding: 0;
  }

  /deep/ .el-input.is-disabled .el-input__inner {
    color: #7f838d;
  }

  /deep/ .choosed-data {
    background-color: #e9f9ff !important;
  }

  .own-form__pic {
    text-align: left;
    padding: 15px 5px;
  }

  /deep/ .own-form__pic .el-form-item__content {
    line-height: 20px !important;
  }

  /deep/ .own-table .el-form-item {
    margin: 18px 0 !important;
  }

  .own-form__pic .upload-demo {
    width: 100%;
    margin: 0;
  }
</style>
